package com.fruit.interceptor;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fruit.pojo.user.SysUser;
import com.fruit.resolver.DefiniteException;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;



public class WapLoginSecurityInterceptor extends HandlerInterceptorAdapter {
	
	@Value("${app.key}")
	private String key;
	
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		
		SysUser sysUser = (SysUser)request.getSession().getAttribute("sysUser");
		
		String requestType = request.getHeader("X-Requested-With");
		if (sysUser == null) {
			// 是否是AJAX登陆
			String forward = request.getServletPath();
			if (UrlConstant.urlMap.containsKey(forward)) {
				forward = UrlConstant.urlMap.get(forward);
			}
			String params = request.getQueryString();
			if(!StringUtils.isEmpty(params)){
				forward +="?"+URLEncoder.encode(params, "UTF-8");
			}
			String contextPath = request.getContextPath();
			if (!StringUtils.equals(requestType,"XMLHttpRequest")) {
				if (StringUtils.isEmpty(forward)) {
					response.sendRedirect(contextPath+"/toLogin");
				} else {
					response.sendRedirect(contextPath+"/toLogin?forward="+forward);
				}
			}else{
				Map<String, Object> resMap = new HashMap<String, Object>();
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "loginOut", "用户未登录","/toLogin"));
				ObjectMapper om = new ObjectMapper();
				response.getWriter().print(om.writeValueAsString(resMap));
			}
			return false;
		}
		
		if (!"0".equals(sysUser.getStatus())) {
			String msg = "该用户已经被禁用，请联系管理员";
			if (!StringUtils.equals(requestType,"XMLHttpRequest")) {
				throw new DefiniteException(msg); 
			}else{
				Map<String, Object> resMap = new HashMap<String, Object>();
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", msg));
				ObjectMapper om = new ObjectMapper();
				response.getWriter().print(om.writeValueAsString(resMap));
			}
		}

		return true;
	}
	
}
